﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using NHibernate;
using HP.Cachalote.Repositories.Interfaces;
using HP.Cachalote.DataModels;

namespace HP.Cachalote.Repositories.NHibernate
{
    public class TodoItemRepository : RepositoryBase<TodoItem>, ITodoItemRepository
    {
        public TodoItemRepository(ISession session) : base(session) { }

        // <summary>
        /// Get TodoItem by id. It will return null if the TodoItem does not exist.
        /// </summary>
        /// <param name="id">The specified id.</param>
        /// /// <param name="loadTodoLabel">True to load related TodoLabel at the same time. False NOT load.</param>
        /// <returns>The matched TodoItem.</returns>
        public TodoItem Get(object id, bool loadTodoLabel)
        {
            var item = base.Get(id);

            if (loadTodoLabel)
            {
                //If you know you need have access to related objects of the TodoItem entity you can use the 
                //NHibernateUtil class to initialize the related objects (that is: to fetch them from the database). 
                NHibernateUtil.Initialize(item.Label);
            }

            return item;
        }

        /// <summary>
        /// Filter TodoItem by lambda expression.
        /// </summary>
        /// <param name="expression">The lambda expression that accepts TodoItem and return boolean.</param>
        /// <param name="loadTodoLabel">True to load related TodoLabel at the same time. False NOT load.</param>
        /// <returns>An IQueryable list of TodoItem.</returns>
        public IQueryable<TodoItem> Filter(Expression<Func<TodoItem, bool>> expression, bool loadTodoLabel)
        {
            var items = base.Filter(expression);

            if (loadTodoLabel)
            {
                foreach (var item in items)
                {
                    //If you know you need have access to related objects of the TodoItem entity you can use the 
                    //NHibernateUtil class to initialize the related objects (that is: to fetch them from the database). 
                    NHibernateUtil.Initialize(item.Label);
                }
            }

            return items;
        }
    }
}
